package com.example.coursehub.service.impl;

import com.example.coursehub.entity.*;
import com.example.coursehub.dto.Identity;
import com.example.coursehub.repository.ClassesRepository;
import com.example.coursehub.repository.CourseRepository;
import com.example.coursehub.repository.CourseStudentRepository;
import com.example.coursehub.repository.CourseTeacherRepository;
import com.example.coursehub.repository.UserRepository; 
import com.example.coursehub.service.CourseService;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.coursehub.repository.*;

import java.util.*;
import java.util.stream.Collectors; 

@Service
public class CourseServiceImpl implements CourseService {

    private final CourseRepository courseRepository;
    private final CourseTeacherRepository courseTeacherRepository;
    private final CourseStudentRepository courseStudentRepository;
    private final ChapterRepository chapterRepository;
    private final ClassesRepository classesRepository;
    private final UserRepository userRepository; 
    private final FavoriteQuestionBankRepository favoriteQuestionBankRepository;
    private final WrongQuestionBankRepository wrongQuestionBankRepository;
    private final JdbcTemplate jdbcTemplate;
    private final CourseQuestionBankRepository courseQuestionBankRepository;

    public CourseServiceImpl(CourseRepository courseRepository,
                             CourseTeacherRepository courseTeacherRepository,
                             CourseStudentRepository courseStudentRepository,
                             ClassesRepository classesRepository,
                             UserRepository userRepository
                             ,ChapterRepository chapterRepository,
                             FavoriteQuestionBankRepository favoriteQuestionBankRepository,
                             WrongQuestionBankRepository wrongQuestionBankRepository,
                             JdbcTemplate jdbcTemplate,
                             CourseQuestionBankRepository courseQuestionBankRepository
                             ) { 

        this.courseRepository = courseRepository;
        this.courseTeacherRepository = courseTeacherRepository;
        this.courseStudentRepository = courseStudentRepository;
        this.classesRepository = classesRepository;
        this.chapterRepository = chapterRepository;
        this.favoriteQuestionBankRepository = favoriteQuestionBankRepository;
        this.wrongQuestionBankRepository = wrongQuestionBankRepository;
        this.jdbcTemplate = jdbcTemplate;
        this.userRepository = userRepository;
        this.courseQuestionBankRepository = courseQuestionBankRepository;
    }



    @Transactional
    @Override
    public Course createCourse(Course course, String userId) {
        if (courseRepository.existsById(course.getCourseId())) {
            throw new RuntimeException("Course with ID " + course.getCourseId() + " already exists.");
        }

        Course savedCourse = courseRepository.saveAndFlush(course);

        // 插入到 course_question_bank 表中
        String courseId = savedCourse.getCourseId();

        String courseQuestionBankId = UUID.randomUUID().toString(); // 生成唯一 ID
        String sql1 = "INSERT INTO course_question_bank (course_question_bank_id, course_id) VALUES (?, ?)";
        jdbcTemplate.update(sql1, courseQuestionBankId, courseId);
        // 插入到 course_teacher 表中
        String sql2 = "INSERT INTO course_teacher (course_id, user_id) VALUES (?, ?)";
        jdbcTemplate.update(sql2, courseId, userId);

        System.out.println("成功插入 course_question_bank 和 course_teacher 数据");

        System.out.println("成功插入course_question_bank数据");
        return savedCourse;
    }

    @Override
    @Transactional
    public Course updateCourse(String courseId, Course courseDetails) {
        Course existingCourse = courseRepository.findById(courseId)
                .orElseThrow(() -> new NoSuchElementException("Course not found with ID: " + courseId));

        existingCourse.setCourseName(courseDetails.getCourseName());
        existingCourse.setTeachingGoal(courseDetails.getTeachingGoal());
        existingCourse.setExaminationMethod(courseDetails.getExaminationMethod());
        existingCourse.setCourse(courseDetails.getCourse());

        return courseRepository.save(existingCourse);
    }

    @Override
    @Transactional
    public void deleteCourse(String courseId) {
        if (!courseRepository.existsById(courseId)) {
            throw new NoSuchElementException("Course not found with ID: " + courseId);
        }
        courseRepository.deleteById(courseId);
    }

    @Override
    @Transactional(readOnly = true)
    public Course getCourseById(String courseId) {
        return courseRepository.findById(courseId)
                .orElseThrow(() -> new NoSuchElementException("Course not found with ID: " + courseId));
    }

    @Override
    @Transactional(readOnly = true)
    public List<Course> getAllCourses() {
        return courseRepository.findAll();
    }


    @Override
    public void deleteMaterial(String materialId, String courseId, String chapterId) {
        throw new UnsupportedOperationException("Deleting material is not supported by this service.");
    }

    @Override
    public void addChapter(String courseId, Chapter chapter) {
        throw new UnsupportedOperationException("Adding chapter is not supported by this service.");
    }

    @Override
    public void addMaterial(String courseId, String chapterId, Material material) {
        throw new UnsupportedOperationException("Adding material is not supported by this service.");
    }

    @Override
    public void deleteChapter(String chapterId, String courseId) {
        throw new UnsupportedOperationException("Deleting chapter is not supported by this service.");
    }
    /**
     * 学生加入课程并初始化收藏与错题记录
     */
    @Transactional
    public void enrollStudentInCourse(String courseId, String userId) {
        // 1. 插入 course_student 关系表
        String sql = "INSERT INTO course_student (course_id, user_id) VALUES (?, ?)";
        jdbcTemplate.update(sql, courseId, userId);

        // 生成唯一 ID
        String favoriteId = UUID.randomUUID().toString();
        String wrongId = UUID.randomUUID().toString();

        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found"));
        Course course = courseRepository.findById(courseId)
                .orElseThrow(() -> new RuntimeException("Course not found"));

        // 3. 创建收藏题库记录
        FavoriteQuestionBank favorite = new FavoriteQuestionBank(favoriteId, user, course);
        favoriteQuestionBankRepository.save(favorite);

        // 4. 创建错题记录
        WrongQuestionBank wrong = new WrongQuestionBank(wrongId, user, course);
        wrongQuestionBankRepository.save(wrong);

    }

    @Override
    @Transactional(readOnly = true)
    public List<Chapter> getChapters(String courseId) {
        return chapterRepository.findByCourse_CourseId(courseId);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Course> getCoursesByUserIdAndRole(String userId, String role) {
        Identity identity = Identity.UNKNOWN;
        try {
            identity = Identity.valueOf(role.toUpperCase());
        } catch (IllegalArgumentException e) {

        }

        List<Course> courses = new ArrayList<>();
        switch (identity) {
            case TEACHER:
            case TEACHING_ASSISTANT:
                courses = getTeacherCourses(userId);
                break;
            case STUDENT:
                courses = getStudentCourses(userId);
                break;
            case UNKNOWN:
                break;
        }
        return courses;
    }

    private List<Course> getTeacherCourses(String userId) {
        List<Course> courses = new ArrayList<>();

        // 1. 查询该教师关联的所有课程记录
        List<CourseTeacher> courseTeachers = courseTeacherRepository.findByUser_UserId(userId);

        // 2. 遍历结果并提取课程信息
        for (CourseTeacher ct : courseTeachers) {
            Course course = ct.getCourse(); // 直接获取关联的 Course 对象
            if (course != null) {
                courses.add(course);
            }
        }

        return courses;
    }
    private List<Course> getStudentCourses(String userId) {
        List<Course> courses = new ArrayList<>();

        // 1. 查询该学生关联的所有课程记录
        List<CourseStudent> courseStudents = courseStudentRepository.findByUser_UserId(userId);

        // 2. 遍历结果并提取课程信息
        for (CourseStudent cs : courseStudents) {
            Course course = cs.getCourse(); // 直接获取关联的 Course 对象
            if (course != null) {
                courses.add(course);
            }
        }

        return courses;
    }

    @Override
    @Transactional(readOnly = true)
    public List<Classes> getClassesByCourseId(String courseId) {
        return classesRepository.findByCourseCourseId(courseId);
    }


    // 新增：课程教师管理方法实现
    @Override
    @Transactional(readOnly = true)
    public List<User> getTeachersInCourse(String courseId) {
        // 查找给定 courseId 的所有 CourseTeacher 实体
        List<CourseTeacher> courseTeachers = courseTeacherRepository.findByCourse_CourseId(courseId);

        // 将它们映射为 User 对象
        return courseTeachers.stream()
                .map(CourseTeacher::getUser)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void addTeacherToCourse(String courseId, String userId) {
        Course course = courseRepository.findById(courseId)
                .orElseThrow(() -> new NoSuchElementException("Course not found with ID: " + courseId));
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new NoSuchElementException("User not found with ID: " + userId));

        // 检查教师是否已分配到该课程
        if (courseTeacherRepository.findByCourse_CourseIdAndUser_UserId(courseId, userId).isPresent()) {
            throw new RuntimeException("Teacher " + user.getUserName() + " is already assigned to course " + course.getCourseName());
        }

        CourseTeacherId courseTeacherId = new CourseTeacherId();
        courseTeacherId.setCourseId(courseId);
        courseTeacherId.setUserId(userId);

        CourseTeacher courseTeacher = new CourseTeacher();
        courseTeacher.setId(courseTeacherId);
        courseTeacher.setCourse(course);
        courseTeacher.setUser(user);

        courseTeacherRepository.save(courseTeacher);
    }

    @Override
    @Transactional
    public void removeTeacherFromCourse(String courseId, String userId) {
        if (!courseTeacherRepository.findByCourse_CourseIdAndUser_UserId(courseId, userId).isPresent()) {
            throw new NoSuchElementException("Teacher " + userId + " not found in course " + courseId);
        }
        courseTeacherRepository.deleteByCourse_CourseIdAndUser_UserId(courseId, userId);
    }

    @Override
    public List<String> getTeachersByCourseId(String courseId) {
        List<CourseTeacher> teachers = courseTeacherRepository.findByCourse_CourseId(courseId);
        return teachers.stream()
                .map(ct -> ct.getUser().getUserName())
                .toList();
    }

//    @Override
//    public Chapter getChapterById(String courseId, String chapterId){
//        return chapterRepository.findByChapter_ChapterIdAndCourse_CourseId(chapterId, courseId)
//                .orElseThrow(() -> new RuntimeException("未找到章节：" + chapterId + " 属于课程：" + courseId));
//    }
}
